package com.csh.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 军哥
 * @version 1.0
 * @description: 文件上传工具类
 * @date 2022/6/24 14:19
 */

public class FileUploadUtil {

    private String uploadDir = "/files";
    private String fileUrl = null;
    private String fileName = null;
    private long fileSize = 0L;
    private String domain = "";

    private FileUploadUtil() {

    }

    public static FileUploadUtil upload() {
        return new FileUploadUtil();
    }

    /**
     * @description 设置上传文件的存储路径
     * @author 军哥
     * @date 2022/1/17 14:31
     * @version 1.0
     */
    public FileUploadUtil setUploadDir(String dir) {
        this.uploadDir = dir;

        return this;
    }

    /**
     * @description 设置全路径URL的域名
     * @author 军哥
     * @date 2022/1/17 14:31
     * @version 1.0
     */
    public FileUploadUtil setDomain(String domain) {
        this.domain = domain;
        return this;
    }

    public String saveFile(MultipartFile file) {
        if(file.isEmpty()){
            return null;
        }

        //-- 获取上传的文件名
        String fileName = file.getOriginalFilename();
        this.fileSize = file.getSize();

        //-- 使用随机文件名，防止文件覆盖
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String newName = UUID.randomUUID().toString();
        newName = newName + suffix;

        File dest = new File(uploadDir + "/" + newName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        try {
            // 保存文件
            file.transferTo(dest);

            // 返回上传的文件信息
            this.fileUrl = newName;
            this.fileName = fileName;
            return newName;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }



    public String getFileName() {
        return this.fileName;
    }

    public String getFileUrl() {
        return this.domain + this.fileUrl;
    }

    public long getFileSize() {
        return this.fileSize;
    }
}

